package NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * @author fei.fang
 * @date 2021/8/24
 **/
public class SelectorServer {

    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));

        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("start");
        while (true) {
            int readChannels = selector.select();
            if (readChannels == 0) {
                continue;
            }

            Set<SelectionKey> readKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = readKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey next = iterator.next();
                iterator.remove();

                if (next.isAcceptable()) {
                    SocketChannel accept = serverSocketChannel.accept();

                    accept.configureBlocking(false);
                    accept.register(selector, SelectionKey.OP_READ);
                }else if(next.isReadable()){
                    SocketChannel channel = (SocketChannel) next.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int read = channel.read(byteBuffer);
                    if (read > 0) {
                        System.out.println("收到数据:" + new String(byteBuffer.array()).trim());
                        ByteBuffer wrap = ByteBuffer.wrap("return data".getBytes(StandardCharsets.UTF_8));
                        channel.write(wrap);
                    } else if (read == -1) {
                        channel.close();
                    }
                }
            }
        }
    }
}
